﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsWorks
{
    public partial class EditiForm : Form
    {
        public EditiForm()
        {
            InitializeComponent();
        }

        public EditiForm(int id, string name, string pwd)
        {
            InitializeComponent();//初始化

            this.id = id;//this 当前的作用域的
            textBox1.Text = name;
            textBox2.Text = pwd;

            
        }
        private int id;

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            var pwdSting = textBox2.Text.ToString();

            var name = textBox1.Text;
            var pwd = pwdSting.Count() > 0 ? int.Parse(pwdSting) : 123456;//默认密码为123456

            //更新
            if (id > 0)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    var sql = 
                        string.Format("update Users set Username='{0}',Password='{1}' where id={2}", name, pwd, this.id);
                    
                    var res = DbHelper.AddOrEditSave(sql);

                    if (res == 1)
                    {
                        MessageBox.Show("更新成功", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                }

            }
            //新增
            else
            {
                if (!string.IsNullOrWhiteSpace(name))//不为空
                {
                    var sql = 
                        string.Format("insert into Users (Username,Password) values('{0}',{1})",name,pwd);

                    var res = DbHelper.AddOrEditSave(sql);

                    if (res == 1)
                    {
                        MessageBox.Show("添加成功", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                    //else  //给机会修改 不直接关闭
                    //{
                    //    MessageBox.Show("添加失败！", "提示");
                    //    this.Close();
                    //}
                }
                else
                {
                    MessageBox.Show("用户名不能为空", "提示");
                }
            }


        }
        /// <summary>
        /// 取消保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }
    }
}
